package com.tgy.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * https://leetcode-cn.com/problems/degree-of-an-array/
 * <p>
 * [1,2,2,3,1,4,2]
 * [2,3,1,2,1]
 */

public class _697_数组的度 {


    public int findShortestSubArray(int[] nums) {

        Map<Integer, Integer> map = new HashMap<>();
        int maxCount = 0;
        for (int num : nums) {

            Integer count = map.get(num);

            if (count == null) {

                count = 1;
            }else {
                count += 1;
            }
            map.put(num,count);
            if (count > maxCount) {
                maxCount = count;
            }
        }

        if (maxCount == 1) {

            return 1;
        }

        int minLen = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {

            Integer count = map.get(nums[i]);

            if (count < maxCount) {
                continue;
            }

            int right = i;
            for (int j = nums.length - 1; j > i; j--) {

                if (nums[j] == nums[i]) {

                    right = j;
                    break;
                }
            }

            minLen = Math.min(minLen, right - i + 1);
            map.put(nums[i],0);
        }

        return minLen;
    }

    public static void main(String[] args) {

        _697_数组的度 findMax = new _697_数组的度();

        int result = findMax.findShortestSubArray(new int[]{1, 2, 2, 3, 1});

        System.out.println(result);

    }
}
